package com.kisyou.blogs;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 所谓软件工程向重构，就是指对代码的改造并不是为了计算机，而仅仅是为了写代码的人而服务，一切的目标是为了让代码更容易让人看懂，后期方便继续升级改造代码。
 *
 * 封装是最核心的方法论。
 * 1）方法级别的封装
 * 2）对象级别的封装
 * // MVC Model View Controller
 * // Model: Blog 对象   【偏向数据向对象】
 * // View: 输入/输出     【偏向流程向对象】
 * // Controller: 逻辑处理【偏向流程向对象】
 */
public class 文章列表分页_方法级别封装 {
    private static int 获取文章总页数(Connection connection, int countPerPage) throws SQLException {
        int count;
        String sql = "select count(*) from blogs";
        try (PreparedStatement ps = connection.prepareStatement(sql)) {
            try (ResultSet rs = ps.executeQuery()) {
                rs.next();

                count = rs.getInt(1);
            }
        }

        int pages = count / countPerPage;
        if (count % countPerPage != 0) {
            pages++;
        }

        return pages;
    }

    private static List<Blog> 根据页数获取文章列表(Connection connection, int countPerPage, int numOfPage) throws SQLException {
        List<Blog> blogList = new ArrayList<>();
        int limit = countPerPage;
        int offset = (numOfPage - 1) * countPerPage;
        String sql = String.format("select bid, title, published_at, author from blogs order by published_at desc limit %d offset %d", limit, offset);
        try (PreparedStatement ps = connection.prepareStatement(sql)) {
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    int bid = rs.getInt("bid");
                    String title = rs.getString("title");
                    String publishedAt = rs.getString("published_at");
                    String author = rs.getString("author");

                    Blog blog = new Blog(bid, title, publishedAt, author);
                    blogList.add(blog);
                }
            }
        }

        return blogList;
    }

    private static void 展示文章列表(List<Blog> blogList) {
        System.out.printf("一共 %d 条博客\n", blogList.size());
        for (Blog blog : blogList) {
            System.out.println(blog);
        }
    }

    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        int countPerPage = 3;
        List<Blog> blogList = null;
        try (Connection c = DBUtil.connection()) {
            int pages = 获取文章总页数(c, countPerPage);
            System.out.printf("一共有 %d 页，请选择第几页:", pages);
            int numOfPage = scanner.nextInt();
            blogList = 根据页数获取文章列表(c, countPerPage, numOfPage);
        }
        展示文章列表(blogList);
    }
}
